import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Pie, Tab

# 读取数据
df__age_distribution = pd.read_excel('C:/Users/DELL/Desktop/课程/数据清洗期末实训/实训资料/data/服饰行业年龄分布.xlsx')

# 按行业名称分组数据
grouped = df__age_distribution.groupby('行业名称')

# 创建Tab对象
tab = Tab()

for industry_name, group_data in grouped:
    # 提取年龄段和占比数据
    age_segments = group_data['年龄段'].tolist()
    proportions = (group_data['占比'] * 100).round(2).tolist()  # 转换为百分比并保留两位小数

    # 绘制饼图
    pie = (
        Pie()
        .add("", [list(z) for z in zip(age_segments, proportions)])
        .set_global_opts(
            title_opts=opts.TitleOpts(title=f"{industry_name} 年龄段占比"),
            legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"),
            toolbox_opts=opts.ToolboxOpts(
                feature={
                    "saveAsImage": {}
                }
            )
        )
        .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}岁: {c}%"))  # 在网页增加单位显示
    )

    # 将饼图添加到Tab对象中
    tab.add(pie, industry_name)

# 渲染为html文件
tab.render("按行业划分的年龄分布.html")
